﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using PISDK;
using PITimeServer;
using Anay.TaskScheduling.Model;

namespace Anay.TaskScheduling
{
    /// <summary>
    /// 访问PI服务器帮助类.
    /// </summary>
    public class PIServerHelper
    {
        private PISDK.PISDK piSDK;   // 定义PISDK接口piSDK
        private Server server;  // 定义Server接口server
        private PointValues values;

        public PIServerHelper()
        {
            piSDK = new PISDKClass();  // 创建PISDKClass对象，并使接口piSDK指向它
            server = piSDK.Servers.DefaultServer; // 使用默认服务器名
        }

        /// <summary>
        /// 建立与PI服务器之间的连接.
        /// </summary>
        public void OpenPIServer()
        {
            try
            {
                if (!server.Connected)
                {
                    Logging.LogHelper.Write("Open connect to PI Server.");
                    string connectString = ConfigurationManager.AppSettings["PIConnectionStr"].ToString(); ;
                    server.Open(connectString);
                }
            }
            catch (Exception ex)
            {
                Logging.LogHelper.Write("Can not connect to PI Server, Exception is: " + ex.Message);
            }
        }

        /// <summary>
        /// 关闭PI服务器之间的连接.
        /// </summary>
        public void ClosePIServer()
        {
            try
            {
                if (server.Connected)
                {
                    server.Close();
                }
            }
            catch (Exception ex)
            {
                Logging.LogHelper.Write("Can not close PI Server, Exception is: " + ex.Message);
            }
        }

        /// <summary>
        /// 从Pi数据库获取历史数据
        /// </summary>
        /// <param name="tagName">查询条件，例如：tag='MM-001-1-S1-0300-S-1000672-022-001'</param>
        /// <param name="startTime">起始时间</param>
        /// <param name="endTime">结束是假你</param>
        /// <param name="filter">过滤条件，如果不需要过滤，请传空</param>
        /// <param name="fvc">显示方式</param>
        /// <returns></returns>
        public virtual List<ExtractData> GetHistoryDataPI(string tagName, DateTime startTime, DateTime endTime,
            string filter = "", FilteredViewConstants fvc = FilteredViewConstants.fvRemoveFiltered)
        {
            List<ExtractData> list = new List<ExtractData>();
            try
            {
                // 开启连接
                OpenPIServer();
                PointList pLst = this.server.GetPoints($"tag='{tagName}'", null);

                // 开始时间
                PITime ptStart = new PITimeClass
                {
                    LocalDate = startTime
                };

                // 结束时间
                PITime ptEnd = new PITimeClass
                {
                    LocalDate = endTime
                };
                foreach (PIPoint piPoint in pLst)
                {
                    PIValues pivalues = piPoint.Data.RecordedValues(ptStart, ptEnd, BoundaryTypeConstants.btInside, filter, fvc);
                    foreach (PIValue p in pivalues)
                    {
                        list.Add(new ExtractData()
                        {
                            Tagid = piPoint.Name,
                            Value = p.Value.ToString(),
                            DateTime = p.TimeStamp.LocalDate,
                        });
                        Logging.LogHelper.Write(string.Format("GetPointValues数据值：Tag:{0}；TagValue：{1}；TagDataTime：{2};", piPoint.Name, p.Value.ToString(), p.TimeStamp.LocalDate));
                    }
                }

            }
            catch (Exception ex)
            {
                throw new Exception("从PI获取历史数据发生错误:" + ex.Message);
            }
            finally
            {
                //ClosePIServer();
            }

            return list;
        }

        /// <summary>
        /// pointvalus 数据取法每次都是指定的几个点
        /// </summary>
        private List<ExtractData> GetPointValues()
        {
            List<ExtractData> list = new List<ExtractData>();
            try
            {
                // 开启连接
                OpenPIServer();
                foreach (PointValue value in values)
                {
                    list.Add(new ExtractData()
                    {
                        Tagid = value.PIPoint.Name,
                        Value = value.PIValue.Value.ToString(),
                        DateTime = value.PIValue.TimeStamp.LocalDate,
                    });
                    Logging.LogHelper.Write(string.Format("GetPointValues数据值：Tag:{0}；TagValue：{1}；TagDataTime：{2};", value.PIPoint.Name, value.PIValue.Value.ToString(), value.PIValue.TimeStamp.LocalDate.ToString()));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("GetPointValues()异常:" + ex.Message);
            }
            finally
            {
                //ClosePIServer();
            }

            return list;
        }
    }
}
